package com.zhongx.xingcd.zxxcd.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Fan
 * Description : 登录拦截器,用户没登录或session过期时,重置到登录页面
 */
public class LoginInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    /**
     * 在请求处理之前进行调用 Controller 方法调用之前,类似前置通知
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String code= (String) session.getAttribute("result");
        //登录了，则判断是否有菜单权限
        System.out.println("路径"+request.getRequestURI()+session.getAttribute("username"));
        if (session.getAttribute("username") != null&&!request.getRequestURI().equals("/logout")) {
            logger.info("------不阻止session有用户名-----"+session.getAttribute("username"));
            return true;
        }else{//!request.getRequestURI().equals("/logout")&&
            if(request.getRequestURI().equals("/login")||request.getRequestURI().equals("/register")||request.getRequestURI().equals("/registerusername")){
                logger.info("------不阻止-----"+session.getAttribute("username"));
                //跳转到登录页

                return true;
            }else if(request.getRequestURI().equals("/logout")){
                session.removeAttribute("username");
                logger.info("------登出-----");
                response.sendRedirect(request.getContextPath()+"/test");
                //跳转到登录页
                return false;
            }else {
                logger.info("------阻止q-----");
                response.sendRedirect(request.getContextPath()+"/test");
                //跳转到登录页
                return false;
            }

        }

    }
    private String substrUri(String uri){
        //第一个/的位置
        int i = uri.indexOf("/");
        //第二个/的位置
        int y = uri.indexOf("/",i+1);
        //第三个/的位置
        int j = uri.indexOf("/",y+1);
        if (j == -1 ){
            return uri;
        }else {
            return uri.substring(0,j);
        }
    }
}
